package com.ljyh.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljyh.forum.entity.Like;
import com.ljyh.forum.entity.Post;
import com.ljyh.forum.mapper.LikeMapper;
import com.ljyh.forum.service.LikeService;
import com.ljyh.forum.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 点赞服务实现类
 */
@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements LikeService {

    @Autowired
    private PostService postService;

    @Override
    @Transactional
    public boolean toggleLike(Long postId, Long userId) {
        QueryWrapper<Like> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("post_id", postId).eq("user_id", userId);
        
        Like existingLike = this.getOne(queryWrapper);
        
        if (existingLike != null) {
            // 取消点赞
            this.remove(queryWrapper);
            updatePostLikeCount(postId, false);
            return false;
        } else {
            // 点赞
            Like like = new Like();
            like.setPostId(postId);
            like.setUserId(userId);
            this.save(like);
            updatePostLikeCount(postId, true);
            return true;
        }
    }

    @Override
    public boolean isLiked(Long postId, Long userId) {
        QueryWrapper<Like> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("post_id", postId).eq("user_id", userId);
        return this.count(queryWrapper) > 0;
    }

    @Override
    public int getLikeCount(Long postId) {
        QueryWrapper<Like> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("post_id", postId);
        return (int) this.count(queryWrapper);
    }

    @Override
    public int getUserLikeCount(Long userId) {
        QueryWrapper<Like> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return (int) this.count(queryWrapper);
    }

    /**
     * 更新帖子的点赞数
     * @param postId 帖子ID
     * @param increment 是否增加（true:增加, false:减少）
     */
    private void updatePostLikeCount(Long postId, boolean increment) {
        Post post = postService.getById(postId);
        if (post != null) {
            int currentLikeCount = post.getLikeCount();
            int newLikeCount = increment ? currentLikeCount + 1 : Math.max(0, currentLikeCount - 1);
            
            postService.lambdaUpdate()
                    .set(Post::getLikeCount, newLikeCount)
                    .eq(Post::getId, postId)
                    .update();
        }
    }
}
